//
//  SEGBillSearchViewController.m
//  SEGUhomePropertyBaseService
//
//  Created by Clavis on 2019/2/26.
//  Copyright © 2019 刘山. All rights reserved.
//

// VC
#import "SEGBillSearchViewController.h"
#import "SEGBillSelectRoomViewController.h"
#import "SEGBillPaymentViewController.h"
// View
#import "SEGAddressView.h"
#import "SEGBillSearchTableViewCell.h"
#import "SEGSelectYearView.h"
// Model
#import "SEGNewBillManager.h"
#import "SEGBillMonthModel.h"

static  NSString *const kCellIdentifier = @"SEGBillSearchTableViewCell";

@interface SEGBillSearchViewController () <UITableViewDelegate, UITableViewDataSource, SEGBillSelectRoomViewDelegate>

@property (nonatomic, strong) SEGAddressView *addressView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSString *houseID;
@property (nonatomic, strong) NSString *houseName;
@property (nonatomic, strong) NSString *custID;
@property (nonatomic, strong) NSString *custType;

// headerView
@property (nonatomic, strong) UILabel *totalAmount;
@property (nonatomic, strong) UIButton *topayButton;
@property (nonatomic, strong) UIButton *unpayButton;
@property (nonatomic, strong) UIButton *nearlyThreeMonthsButton;
@property (nonatomic, strong) UIButton *nearlySixMonthsButton;
@property (nonatomic, strong) UIButton *selectYearButton;

@property (nonatomic, strong) SEGNewBillManager *manager;
@property (nonatomic, strong) NSMutableDictionary<NSNumber *, NSMutableArray<SEGBillMonthModel *>*> *dataSource;
@property (nonatomic, strong) NSArray<NSNumber *> *allYears;

@end

@implementation SEGBillSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self loadHouseList];
}

- (void)setupUI {
    self.title = self.title.length>0?self.title : @"账单查询";
    self.view.backgroundColor = kColor_W;
    
    self.addressView = [[SEGAddressView alloc] init];
    self.addressView.backgroundColor = kColor_W;
    [self.addressView.titleBtn addTarget:self action:@selector(changeAddress:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.addressView];
    [self.addressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
    }];
    
    self.tableView = ({
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = kColor_W;
        tableView.tableFooterView = [[UIView alloc] init];
        tableView.estimatedRowHeight = 44.0f;
        tableView.rowHeight = UITableViewAutomaticDimension;
        [tableView registerClass:[SEGBillSearchTableViewCell class] forCellReuseIdentifier:kCellIdentifier];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:tableView];
        tableView;
    });
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.addressView.mas_bottom);
    }];
    
    [self setupHeaderView];
}

- (void)setupHeaderView {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), 179)];
    headerView.backgroundColor = kColor_W;
    
    UIView *amountBackView = [[UIView alloc] init];
    amountBackView.backgroundColor = [UIColor colorWithHexString:@"#FFB014"];
    amountBackView.backgroundColor = kColor_T;
    amountBackView.layer.cornerRadius = 5;
    [headerView addSubview:amountBackView];
    [amountBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(110);
    }];
    
    UILabel *tipLabel = ({
        UILabel *lable = [[UILabel alloc] init];
        [amountBackView addSubview:lable];
        lable.textColor = kColor_W;
        lable.font = [UIFont boldSystemFontOfSize:13];
        lable.text = @"当前待缴";
        lable;
    });
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(20);
        make.left.mas_equalTo(15);
    }];
    
    self.totalAmount = ({
        UILabel *lable = [[UILabel alloc] init];
        [amountBackView addSubview:lable];
        lable.textColor = kColor_W;
        lable.font = [UIFont boldSystemFontOfSize:33];
        NSMutableAttributedString *amountString = [[NSMutableAttributedString alloc] initWithString:@"￥" attributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:22]}];
        [amountString appendAttributedString:[[NSAttributedString alloc] initWithString:@"0.00" attributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:33]}]];
        lable.attributedText = amountString;
        lable;
    });
    [self.totalAmount mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(tipLabel.mas_left);
        make.top.equalTo(tipLabel.mas_bottom).offset(17);
    }];
    
    self.topayButton = ({
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"去缴费  " forState:UIControlStateNormal];
        [button setTitleColor:kColor_1 forState:UIControlStateNormal];
        button.titleLabel.font = kFont_13;
        [button setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"img_pocketmoney_arrow_w")] forState:UIControlStateNormal];
        [button setTitleColor:kColor_W forState:UIControlStateNormal];
        button.imageEdgeInsets = UIEdgeInsetsMake(0, 46, 0, 0);
        button.titleEdgeInsets = UIEdgeInsetsMake(0, -9, 0, 0);
        [button addTarget:self action:@selector(gotoPayButtonTap:) forControlEvents:UIControlEventTouchUpInside];
        button.hidden = YES;
        [amountBackView addSubview:button];
        button;
    });
    
    [self.topayButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.totalAmount.mas_bottom);
        make.right.mas_equalTo(-15);
    }];
    
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = kColor_bg;
    [headerView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(amountBackView.mas_bottom).offset(20);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(5);
    }];
    
    UIView *selectButtonBackView = [[UIView alloc] init];
    [headerView addSubview:selectButtonBackView];
    [selectButtonBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.equalTo(lineView.mas_bottom);
    }];
    
    self.unpayButton = [self createSelectButtonWith:selectButtonBackView index:1 title:@"未缴清" action:@selector(selectUnpayButtonTap:)];
    self.unpayButton.selected = YES;
    self.unpayButton.userInteractionEnabled = NO;
    self.nearlyThreeMonthsButton = [self createSelectButtonWith:selectButtonBackView index:2 title:@"近三个月" action:@selector(selectNearlyThreeMonthsButtonTap:)];
    self.nearlySixMonthsButton = [self createSelectButtonWith:selectButtonBackView index:3 title:@"近六个月" action:@selector(selectNearlySixMonthsButtonTap:)];
    
    UIImageView *arrowImage = ({
        UIImageView *imageView = [[UIImageView alloc] init];
        [selectButtonBackView addSubview:imageView];
        imageView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"btn_year_celect")];
        imageView;
    });
    [arrowImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-15);
        make.centerY.mas_offset(0);
    }];
    
    self.selectYearButton = ({
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"年份筛选" forState:UIControlStateNormal];
        [button setTitleColor:kColor_1 forState:UIControlStateNormal];
        [button setTitleColor:kColor_T forState:UIControlStateSelected];
        button.titleLabel.font = kFont_13;
        button.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 15);
        [button addTarget:self action:@selector(selectYearButtonTap:) forControlEvents:UIControlEventTouchUpInside];
        [selectButtonBackView addSubview:button];
        button;
    });
    [self.selectYearButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(arrowImage.mas_right);
        make.centerY.mas_offset(0);
        make.height.mas_equalTo(30);
    }];
    
    UIView *verticalLine = [[UIView alloc] init];
    verticalLine.backgroundColor = kColor_L2;
    [selectButtonBackView addSubview:verticalLine];
    [verticalLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_offset(0);
        CGFloat margin = LYScreenWidth() == 320 ? -ceil(LYScreenWidth()/4.0) - 11 : -ceil(LYScreenWidth()/4.0);
        make.right.mas_equalTo(margin);
        make.height.mas_equalTo(18);
        make.width.mas_equalTo(1);
    }];
    
    UIView *horizontalLine = [[UIView alloc] init];
    horizontalLine.backgroundColor = kColor_L2;
    [selectButtonBackView addSubview:horizontalLine];
    [horizontalLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_offset(0);
        make.height.mas_equalTo(1);
    }];
    
    self.tableView.tableHeaderView = headerView;
}

- (UIButton *)createSelectButtonWith:(UIView *)superView index:(NSInteger)index title:(NSString *)title action:(SEL)action  {
    UIButton *button = ({
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:title forState:UIControlStateNormal];
        [button setTitleColor:kColor_1 forState:UIControlStateNormal];
        [button setTitleColor:kColor_W forState:UIControlStateSelected];
        [button setTitleColor:kColor_W forState:UIControlStateHighlighted];
        button.titleLabel.font = kFont_13;
        [button setBackgroundImage:nil forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageWithColor:kColor_T] forState:UIControlStateSelected];
        [button setBackgroundImage:[UIImage imageWithColor:kColor_T] forState:UIControlStateHighlighted];
        button.layer.cornerRadius = 12;
        button.layer.masksToBounds = YES;
        button.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 10);
        [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
        [superView addSubview:button];
        button;
    });
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_offset(0);
        // 5s 上布局做适配
        CGFloat adjustMargin = (LYScreenWidth() == 320 && index > 1) ? 6 * index : 0;
        make.centerX.mas_offset(ceil(LYScreenWidth()/8.0*(2*index-1) - LYScreenWidth()/2.0) - adjustMargin);
        make.height.mas_equalTo(24);
    }];
    return button;
}

- (void)resetTableViewData {
    self.dataSource = [NSMutableDictionary dictionary];
    self.allYears = [NSArray array];
    [self.tableView reloadData];
}

- (void)resetTotalAmount {
    // 更新欠费总金额
    NSMutableAttributedString *amountString = [[NSMutableAttributedString alloc] initWithString:@"￥" attributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:22]}];
    [amountString appendAttributedString:[[NSAttributedString alloc] initWithString:@"0.00" attributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:33]}]];
    self.totalAmount.attributedText = amountString;
    self.topayButton.hidden = YES;
}

// 更新是否显示默认图
- (void)updateTablePlaceHolderView {
    if (self.dataSource.count == 0) {
        [[SEGUhomeMediator sharedInstance] seg_showCustomProgressImage:@{@"view":self.tableView, @"text":@"暂无账单", @"image":@"pic_default_nobills", @"origin.y":@(179)}];
    } else {
        [[SEGUhomeMediator sharedInstance] seg_hideCustomProgressImage:@{@"view":self.tableView, @"text":@"暂无账单", @"image":@"pic_default_nobills", @"origin.y":@(179)}];
    }
}

#pragma mark - action
- (void)changeAddress:(UIButton *)sender {
    SEGBillSelectRoomViewController* selectRoomVC = [[SEGBillSelectRoomViewController alloc] init];
    selectRoomVC.houseId = self.houseID;
    selectRoomVC.hidesBottomBarWhenPushed = YES;
    selectRoomVC.delegate = self;
    [self.navigationController pushViewController:selectRoomVC animated:YES];
}

- (void)gotoPayButtonTap:(UIButton *)sender {
    SEGBillPaymentViewController *billPaymentVC = [[SEGBillPaymentViewController alloc] init];
    billPaymentVC.houseID = self.houseID;
    billPaymentVC.houseName = self.houseName;
    billPaymentVC.custID = self.custID;
    billPaymentVC.custType = self.custType;
    [self.navigationController pushViewController:billPaymentVC animated:YES];
}

- (void)selectUnpayButtonTap:(UIButton *)sender {
    if (sender.selected) {
        return;
    }
    [self resetButtonStatus];
    [self resetTableViewData];
    sender.selected = YES;
    sender.userInteractionEnabled = NO;
    
    [self loadBillData];
}

- (void)selectNearlyThreeMonthsButtonTap:(UIButton *)sender {
    if (sender.selected) {
        return;
    }
    [self resetButtonStatus];
    [self resetTableViewData];
    sender.selected = YES;
    sender.userInteractionEnabled = NO;
    
    [self loadBillWithBeginDate:[SEGNewBillManager calculateTimeBeseNowWithIntervalMonth:-2] endDate:[SEGNewBillManager currentTimeString]];
}

- (void)selectNearlySixMonthsButtonTap:(UIButton *)sender {
    if (sender.selected) {
        return;
    }
    [self resetButtonStatus];
    [self resetTableViewData];
    sender.selected = YES;
    sender.userInteractionEnabled = NO;
    
    [self loadBillWithBeginDate:[SEGNewBillManager calculateTimeBeseNowWithIntervalMonth:-5] endDate:[SEGNewBillManager currentTimeString]];
}

- (void)selectYearButtonTap:(UIButton *)sender {
    SEGSelectYearView *selectView = [[SEGSelectYearView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    selectView.alpha = 0;
    [[UIApplication sharedApplication].keyWindow addSubview:selectView];
    [UIView animateWithDuration:0.3 animations:^{
        selectView.alpha = 1;
    }];
    WeakSelf;
    selectView.comfirmBlock = ^(NSInteger selectYear) {
        if (!sender.selected) {
            [weakSelf resetButtonStatus];
        }
        
        [sender setTitle:[NSString stringWithFormat:@"%ld年", (long)selectYear] forState:UIControlStateNormal];
        sender.selected = YES;
        NSString *beginDate = [NSString stringWithFormat:@"%ld01", (long)selectYear];
        NSString *endDate = [NSString stringWithFormat:@"%ld12", (long)selectYear];
        [weakSelf resetTableViewData];
        [weakSelf loadBillWithBeginDate:beginDate endDate:endDate];
    };
}

- (void)resetButtonStatus {
    self.unpayButton.selected = NO;
    self.selectYearButton.selected = NO;
    self.nearlyThreeMonthsButton.selected = NO;
    self.nearlySixMonthsButton.selected = NO;
    
    self.unpayButton.userInteractionEnabled = YES;
    self.nearlyThreeMonthsButton.userInteractionEnabled = YES;
    self.nearlySixMonthsButton.userInteractionEnabled = YES;
    
    [self.selectYearButton setTitle:@"年份筛选" forState:UIControlStateNormal];
}

#pragma mark - SEGBillSelectRoomViewDelegate - 切换小区
- (void)cell_didSelectedRoom:(SEGProfileHouselistModel *)data {
    self.houseID = data.houseId;
    self.houseName = data.fullHouseName;
    self.custID = self.custID;
    self.custType = self.custType;
    self.addressView.contentLabel.text = self.houseName;
    [self resetButtonStatus];
    self.unpayButton.selected = YES;
    self.unpayButton.userInteractionEnabled = NO;
    [self resetTableViewData];
    [self resetTotalAmount];
    [self loadBillData];
}

#pragma mark - <UITableViewDelegate, UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.allValues.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSNumber *year = [self.allYears objectAtIndex:section];
    NSArray *monthBills = [self.dataSource objectForKey:year];
    return monthBills.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SEGBillSearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier forIndexPath:indexPath];
    
    NSNumber *year = self.allYears[indexPath.section];
    NSMutableArray<SEGBillMonthModel *> *billsInYear = [[self.dataSource objectForKey:year] mutableCopy];
    SEGBillMonthModel *model = billsInYear[indexPath.row];
    [cell updateUIWithModel:model];
    
    WeakSelf;
    cell.switchBlcok = ^(BOOL isSelect) {
        model.isSelect = isSelect;
        billsInYear[indexPath.row] = model;
        weakSelf.dataSource[year] = [billsInYear copy];
        [weakSelf.tableView reloadData];
    };
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] init];
    UILabel *yearLabel = ({
        UILabel *lable = [[UILabel alloc] init];
        [headerView addSubview:lable];
        lable.textColor = kColor_3;
        lable.font = kFont_15;
        lable;
    });
    [yearLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.bottom.mas_equalTo(-5);
    }];
    yearLabel.text = [NSString stringWithFormat:@"%@年", [self.allYears objectAtIndex:section]];
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

#pragma mark - Data Handle
- (void)loadHouseList {
    // 不再请求房屋列表，直接使用用户数据返回的数据
    SEGProfileModel *userAccount = [SEGProfileManager sharedManager].profile;
    if (userAccount.houseList.count == 0) {
        self.addressView.contentLabel.text = @"没有可用的小区！";
        return;
    }
    
    self.houseID = userAccount.houseId;
    self.houseName = userAccount.houseName;
    self.custID = userAccount.custId;
    self.custType = userAccount.defaultCustType;
    self.addressView.contentLabel.text = self.houseName;
    
    [self loadBillData];
}

- (void)loadBillData {
    if (self.houseID.length == 0) {
        return;
    }
    
    NSString *communityId = kAccountCommunityID ?: @"";
    NSDictionary *params = @{@"houseId":self.houseID, @"communityId":communityId, @"custId":self.custID, @"custType":self.custType};
    
    WeakSelf;
    [SVProgressHUD show];
    [self.manager requestOweBillListWithParamsDic:params finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
        [SVProgressHUD dismiss];
        if (!isSuccessed) {
            [SEGAlertView showTmepMessageWithMessage:errorMessage];
            return;
        }
        
        // 更新欠费总金额
        NSMutableAttributedString *amountString = [[NSMutableAttributedString alloc] initWithString:@"￥" attributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:22]}];
        [amountString appendAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%.2f", weakSelf.manager.oweAmount] attributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:33]}]];
        weakSelf.totalAmount.attributedText = amountString;
        weakSelf.topayButton.hidden = weakSelf.manager.oweAmount <= 0;
        // 更新按钮状态
        [weakSelf resetButtonStatus];
        weakSelf.unpayButton.selected = YES;
        weakSelf.unpayButton.userInteractionEnabled = NO;
        weakSelf.dataSource = weakSelf.manager.billYearDic;
        weakSelf.allYears = [weakSelf.manager.allYears copy];
        [weakSelf.tableView reloadData];
        [weakSelf updateTablePlaceHolderView];
    }];
}


/**
 加载指定时间的账单
 */
- (void)loadBillWithBeginDate:(NSString *)beginDate endDate:(NSString *)endDate {
    if (self.houseID.length == 0) {
        return;
    }
    
    NSString *communityId = kAccountCommunityID ?: @"";
    NSDictionary *params = @{@"houseId":self.houseID, @"billingCycle":beginDate, @"endCycleId":endDate, @"communityId":communityId, @"custId":self.custID, @"custType":self.custType};
    
    WeakSelf;
    [SVProgressHUD show];
    [self.manager requestBillListWithParamsDic:params finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
        [SVProgressHUD dismiss];
        if (!isSuccessed) {
            [SEGAlertView showTmepMessageWithMessage:errorMessage];
            return;
        }
        
        weakSelf.dataSource = weakSelf.manager.billYearDic;
        weakSelf.allYears = [weakSelf.manager.allYears copy];
        [weakSelf.tableView reloadData];
        [weakSelf updateTablePlaceHolderView];
    }];
}

#pragma mark - Getter & Setter
- (SEGNewBillManager *)manager {
    if (!_manager) {
        _manager = [[SEGNewBillManager alloc] init];
    }
    return _manager;
}

@end
